import io
import re
from zipfile import ZipFile
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from web.models import Public_Src, User, Files
from datetime import datetime
from web.utils import utils


@csrf_exempt
@require_http_methods(["GET"])
def getPath(request):
    path = request.GET.get("src_path", None)
    type = request.GET.get("type", None)
    if type == "文件夹":
        path = path.replace("/", "+")
        path = "http://127.0.0.1:8000/shared/detailDirs/" + path
    else:
        ID = Files.objects.filter(path=path).values("ID")
        path = "http://127.0.0.1:8000/shared/doc/read/" + str(ID[0]["ID"])
    return HttpResponse(path)


# 初始化
def index(request):
    query = request.GET.get("query", None)
    # 默认链接
    itemLinks = [{"name": "Home", "url": "/shared"}]
    # 获取所有信息，按照发布时间降序排列
    filesList = []
    # type是在添加时判断
    # 'ID', 'user_ID', 'src_path', 'type', 'upload_time', 'num_stars'
    if query == None:
        files = Public_Src.objects.values().all().order_by("-upload_time")
    else:
        # 显示符合要求的过滤资源   Files.name = query && Files.path == Publi_Src.src_path
        allPath = Public_Src.objects.values("src_path").all().order_by("-upload_time")
        files1 = (
            Files.objects.values("path", "name", "user_ID", "m_time")
            .filter(path__contains=query)
            .order_by("-m_time")
        )
        files = []
        for i in range(len(files1)):
            for j in range(len(allPath)):
                try:
                    re.match(allPath[j]["src_path"], files1[i]["path"]).group()
                    # 不报错则匹配成功  有一个匹配成功即可
                    tem = {
                        "user_ID": files1[i]["user_ID"],
                        "src_path": files1[i]["path"],
                        "upload_time": files1[i]["m_time"],
                        "num_stars": 0,
                    }
                    tem["type"] = utils.isFilesOrDirs(
                        files1[i]["path"], files1[i]["user_ID"]
                    )
                    files.append(tem)
                    break
                except:
                    pass
        # 将链接加入
        r = {"name": query.split("/")[-1] + " 查找结果如下", "url": "#"}
        itemLinks.append(r)

    # 添加所有路径  需要用户ID
    filesPath = Files.objects.values("path").filter(user_ID=request.session.get("ID"))
    myFilePath = []
    for i in range(len(filesPath)):
        paths = filesPath[i]["path"].split("/")
        item = ""
        for k in range(1, len(paths)):
            item = item + "/" + paths[k]
            if item not in myFilePath:
                myFilePath.append(item)

    # 要显示全部资源，不需要用户ID
    for i in range(len(files)):
        # 根据 user_ID 找到 username，加入到列表的相应字典中
        username = User.objects.values("username").get(pk=files[i]["user_ID"])
        files[i]["username"] = username["username"]
        # 根据路径命名文件夹
        files[i]["filename"] = files[i]["src_path"].split("/")[-1]
        # 根据 user_id 找到 文件 的 name 与 size，加入到列表的相应字典中
        t = Files.objects.values("path", "size").filter(
            user_ID=int(files[i]["user_ID"])
        )
        # 获取该路径下的所有文件的大小之和
        size = 0
        for j in range(len(t)):
            try:
                re.match(files[i]["src_path"], t[j]["path"]).group()
                # 不报错则匹配成功
                size = size + int(t[j]["size"])
            except:
                pass
        files[i]["size"] = size
        key = [
            "user_ID",
            "type",
            "src_path",
            "filename",
            "username",
            "upload_time",
            "size",
            "num_stars",
        ]
        temp = {}
        for j in range(len(key)):
            temp[key[j]] = files[i][key[j]]
        filesList.append(temp)

    return render(
        request,
        "web/sharedSpace.html",
        {
            "filesList": filesList,
            "isDetail": False,
            "itemLinks": itemLinks,
            "myFilePath": myFilePath,
        },
    )


# 上传
@csrf_exempt
@require_http_methods(["POST"])
def upload(request):
    user_ID = request.session.get("ID")
    src_path = request.POST.get("src_path", None)
    message = ""
    # 先检查是否已经存在
    if Public_Src.objects.filter(user_ID=user_ID, src_path=src_path).exists():
        message = "文件已上传，禁止重复上传相同文件！"
    else:
        #  ID upload_time user_ID type src_path num_stars
        upload_time = datetime.now()
        type = utils.isFilesOrDirs(src_path, user_ID)
        Public_Src.objects.create(
            upload_time=upload_time,
            user_ID=user_ID,
            type=type,
            src_path=src_path,
            num_stars=0,
        )
        message = "上传成功！"
    return HttpResponse(message)


# 文件夹详情
@csrf_exempt
@require_http_methods(["GET"])
def detailDirs(request, item):
    # path = request.GET.get('path',None)
    path = item.replace("+", "/")
    # 默认链接
    itemLinks = [{"name": "Home", "url": "/shared"}]
    # 添加所有链接
    itempath = path.split("/")
    currentPath = ""
    for i in range(1, len(itempath)):
        currentPath = currentPath + "+" + itempath[i]
        c = {"name": itempath[i], "url": "/shared/detailDirs/" + currentPath}
        itemLinks.append(c)

    file = Files.objects.values().filter(user_ID=request.session.get("ID"))
    # 获取该路径下的一级文件名称
    fileList = []
    # 记录子路径，避免重复计算
    childPath = []
    for i in range(len(file)):
        # 在t[i]['path']中去除src_path
        f = file[i]["path"].replace(path, "", 1)
        if f != file[i]["path"] and f != "":
            temp = path + "/" + f.split("/")[1]
            if temp not in childPath:
                childPath.append(temp)
                Dirs = utils.toDirs(temp, request.session.get("ID"))
                fileList.append(Dirs)
    return render(
        request,
        "web/sharedDetail.html",
        {"filesList": fileList, "isDetail": True, "itemLinks": itemLinks},
    )


# 搜索功能
@require_http_methods(["GET"])
def search(request):
    query = request.GET.get("query")
    return JsonResponse({"href": "/shared?query=" + query})


# 下载功能
@require_http_methods(["GET"])
def download(request):
    path = request.GET.get("src_path")
    user_ID = request.GET.get("user_ID")
    # 创建zip文件
    # 名称
    buffer = io.BytesIO()
    file_name = path.split("/")[-1]

    zip = ZipFile(buffer, mode="w")
    # 文件路径和内容
    file = Files.objects.filter(path__contains=path, user_ID=user_ID).values()
    for i in range(len(file)):
        # 写入zip文件
        path = file[i]["path"]
        content = file[i]["content"]
        zip.writestr(path, content)
    zip.close()

    response = HttpResponse(buffer.getvalue())
    response["Content-Type"] = "application/octet-stream"
    response["Content-Disposition"] = "attachment; filename=" + file_name
    return response
